package com.xianggu.designMode.chainMethod.demo04;

import com.xianggu.designMode.chainMethod.demo03.Order;
import com.xianggu.designMode.chainMethod.demo03.OrderHandler;
import com.xianggu.designMode.chainMethod.demo03.OrderResult;
import com.xianggu.designMode.chainMethod.demo03.impl.ObservableHandler;
import com.xianggu.designMode.chainMethod.demo03.impl.PaymentHandler;
import com.xianggu.designMode.chainMethod.demo03.impl.ShippingHandler;
import com.xianggu.designMode.chainMethod.demo04.impl.EmailNotificationListener;
import com.xianggu.designMode.chainMethod.demo04.impl.InventoryHandler;
import com.xianggu.designMode.chainMethod.demo04.impl.LoggingListener;

public class OrderProcessingClient {
    //在职责链模式的基础上，增加观察者模式的功能：当订单处理失败时，触发通知机制（如发送邮件、记录日志等）。
    public static void main(String[] args) {
        // 创建订单
        Order order = new Order("20231015001", "user123", 5, 999.99, false, "北京市海淀区");

        // 创建处理链
        OrderHandler chain = new InventoryHandler();
        chain.setNext(new PaymentHandler())
                .setNext(new ShippingHandler());


        // 注册观察者（日志记录器和邮件通知器）
        if (chain instanceof ObservableHandler) {
            ObservableHandler observableChain = (ObservableHandler) chain;
            observableChain.addListener(new LoggingListener());
            observableChain.addListener(new EmailNotificationListener());
        }

        // 执行处理
        OrderResult result = chain.handle(order);
        if (result.isSuccess()) {
            System.out.println("订单处理成功!");
        } else {
            System.out.printf("订单处理失败：%s（失败环节：%s）%n", 
                result.getMessage(), result.getFailedStep());
            if (chain instanceof ObservableHandler) {
                ObservableHandler observableChain = (ObservableHandler) chain;
                observableChain.notifyFailure(order, result.getFailedStep());
            }
        }
    }
}